const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const fs = require('fs');
const CrawlerScheduler = require('./scheduler');

/**
 * 百度热搜爬虫Web服务器
 */
class CrawlerServer {
  constructor(port = 3000) {
    this.port = port;
    this.app = express();
    this.scheduler = new CrawlerScheduler();
    this.setupServer();
  }

  /**
   * 设置Express服务器
   */
  setupServer() {
    // 配置中间件
    this.app.use(bodyParser.json());
    this.app.use(bodyParser.urlencoded({ extended: true }));
    this.app.use(express.static(path.join(__dirname, '../public')));
    
    // 设置模板引擎
    this.app.set('view engine', 'ejs');
    this.app.set('views', path.join(__dirname, '../views'));
    
    // 配置路由
    this.setupRoutes();
  }

  /**
   * 设置路由
   */
  setupRoutes() {
    // 主页 - 热搜控制面板
    this.app.get('/', (req, res) => {
      const latestData = this.scheduler.getLatestHotSearch();
      res.render('index', {
        hotSearchData: latestData.success ? latestData.data : [],
        isScheduleRunning: !!this.scheduler.task,
        timestamp: new Date().toLocaleString()
      });
    });
    
    // API: 获取最新热搜
    this.app.get('/api/hot', (req, res) => {
      const latestData = this.scheduler.getLatestHotSearch();
      res.json(latestData);
    });
    
    // API: 获取历史热搜数据
    this.app.get('/api/history', (req, res) => {
      const historyData = this.scheduler.getHistoryData();
      res.json({
        success: true,
        history: historyData
      });
    });
    
    // API: 获取特定历史数据
    this.app.get('/api/history/:date/:time', (req, res) => {
      const { date, time } = req.params;
      
      try {
        const filePath = path.join(process.cwd(), 'data', date, `baidu_hot_${time}.json`);
        
        if (!fs.existsSync(filePath)) {
          return res.status(404).json({
            success: false,
            message: '未找到指定的历史数据'
          });
        }
        
        const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
        res.json({
          success: true,
          data,
          date,
          time
        });
      } catch (error) {
        res.status(500).json({
          success: false,
          message: `获取历史数据失败: ${error.message}`
        });
      }
    });
    
    // API: 手动爬取热搜
    this.app.post('/api/crawl', async (req, res) => {
      try {
        const result = await this.scheduler.manualCrawl();
        res.json(result);
      } catch (error) {
        res.status(500).json({
          success: false,
          message: `爬取失败: ${error.message}`
        });
      }
    });
    
    // API: 启动定时任务
    this.app.post('/api/schedule/start', (req, res) => {
      const { cron } = req.body;
      const started = this.scheduler.startSchedule(cron);
      
      if (started && cron) {
        // 更新配置
        this.scheduler.updateConfig({ cronExpression: cron });
      }
      
      res.json({
        success: true,
        started,
        message: started ? '定时任务已启动' : '定时任务已在运行中'
      });
    });
    
    // API: 停止定时任务
    this.app.post('/api/schedule/stop', (req, res) => {
      const stopped = this.scheduler.stopSchedule();
      
      res.json({
        success: true,
        stopped,
        message: stopped ? '定时任务已停止' : '没有运行中的定时任务'
      });
    });
    
    // API: 获取配置
    this.app.get('/api/config', (req, res) => {
      res.json({
        success: true,
        config: this.scheduler.config
      });
    });
    
    // API: 更新配置
    this.app.post('/api/config', (req, res) => {
      try {
        const newConfig = req.body;
        const updatedConfig = this.scheduler.updateConfig(newConfig);
        
        res.json({
          success: true,
          config: updatedConfig,
          message: '配置已更新'
        });
      } catch (error) {
        res.status(500).json({
          success: false,
          message: `更新配置失败: ${error.message}`
        });
      }
    });
  }

  /**
   * 启动服务器
   */
  start() {
    this.server = this.app.listen(this.port, () => {
      console.log(`爬虫服务器已启动，访问地址: http://localhost:${this.port}`);
      
      // 如果配置了自动启动定时任务
      if (this.scheduler.config.autoStartSchedule) {
        this.scheduler.startSchedule();
      }
    });
    
    return this.server;
  }

  /**
   * 停止服务器
   */
  stop() {
    if (this.server) {
      this.scheduler.stopSchedule();
      this.server.close();
      console.log('爬虫服务器已停止');
    }
  }
}

module.exports = CrawlerServer; 